<?php


namespace app\admin\controller;


use think\Db;

class Message
{
        public function insert_Message(){
            $fromid=$_POST['fromid'];
            $toid=$_POST['toid'];
            $message=$_POST['message'];
            $time=$_POST['time'];
            $isread=$_POST['isread'];

            $data=["fromid"=>$fromid,"toid"=>$toid,"message"=>$message,"time"=>$time,"isread"=>$isread];
            $affect_row=Db::table("message")->insert($data);
            if($affect_row){
                $res=["state"=>200,"type"=>"success"];
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
            }else{
                $res=["state"=>400,"type"=>"fail"];
                echo json_encode($res,JSON_UNESCAPED_UNICODE);
            }
        }

        public function select_Message(){
            $fromid=$_POST['fromid'];
            $toid=$_POST['toid'];

            //( (fromid = $fromid) and (toid = $toid) )
            //( (fromid = $toid) and (toid = $fromid) )

            //如果没有数据则返回 [] 数组
            $res=Db::query("select * from message where( ( (fromid = $fromid) and (toid = $toid) ) or ( (fromid = $toid) and (toid = $fromid) ) )");

            //如果消息记录大于205条则删除前100条
            if(sizeof($res)>205){
                $all_id=Db::query("select id from message where( ( (fromid = $fromid) and (toid = $toid) ) or ( (fromid = $toid) and (toid = $fromid) ) )");
                $all_id=array_slice($all_id,0,100);
                Db::table('message')->delete($all_id);
                $res=Db::query("select * from message where( ( (fromid = $fromid) and (toid = $toid) ) or ( (fromid = $toid) and (toid = $fromid) ) )");
            }

            echo json_encode($res,JSON_UNESCAPED_UNICODE);
        }
}